
#include "oal.h"
#include "driver_audio.h"

#include "oal_mem.h"
#include <stdio.h>
#include <windows.h>
#include <assert.h>
#pragma comment(lib, "winmm.lib") 

typedef struct {
	file_operations_t fops;
	driver_audio_open_opt_t opt;
	struct pcm_config cfg;
	struct pcm* in;
	struct pcm* out;

}drv_audio_fops;



static int _open0(handle_t handle, int flag, void* opt)
{
	flag = flag;
	if (!opt) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	_this->opt = *(driver_audio_open_opt_t*)opt;
	_this->cfg = _this->opt.cfg;
	_this->out = pcm_open(1, PCM_OUT, &_this->cfg);
	return 0;
}

static int _open1(handle_t handle, int flag, void* opt)
{
	flag = flag;
	if (!opt) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	_this->opt = *(driver_audio_open_opt_t*)opt;
	_this->cfg = _this->opt.cfg;

	_this->in= pcm_open(1, PCM_IN, &_this->cfg);
	return 0;
}

static ssize_t _read(handle_t handle, char* buf, size_t size, loff_t* ppos)
{
	ppos = ppos;
	if (!handle) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	int ret = pcm_read(_this->in, buf, size);
	return ret;
}

static ssize_t _write(handle_t handle, const char* buf, size_t size, loff_t* ppos)
{
	ppos = ppos;
	if (!handle) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	int ret = pcm_write(_this->out, buf, size);
	return ret;
}

static int _close0(handle_t handle)
{
	if (!handle) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	int ret = pcm_close(_this->out);
	return ret;
}

static int _close1(handle_t handle)
{
	if (!handle) return -1;
	drv_audio_fops* _this = (drv_audio_fops*)handle;
	int ret = pcm_close(_this->in);
	return ret;
}

static int _ioctl(handle_t handle, unsigned int cmd, void* opt)
{
	handle = handle;
	cmd = cmd;
	opt = opt;
	return 0;
}
static file_operations_t* Create(unsigned int ver)
{
	file_operations_t* p = (file_operations_t*)OAL_calloc(1, sizeof(drv_audio_fops));
	if (p) {
		if (ver == 0) {
			//_codec_init();
			p->open = _open0;
			p->release = _close0;
			p->write = _write;
		}
		else if (ver == 1) {
			p->open = _open1;
			p->release = _close1;
			p->read = _read;
		}
		p->ioctl = _ioctl;
	}
	return p;
}


const dev_description_t g_audio0_dev_description = {
	.Create = Create,
	.major = 0,
	.minor = 0,
	.name = "/dev/audio0",
};

const dev_description_t g_audio1_dev_description = {
	.Create = Create,
	 0,
	 1,
	"/dev/audio1",
};

